const eventsHolder = {
	observerList: [],//观察对象列表
	stickyEvents: [],//粘性事件(消息)
}
type Subscriber = (msg: any) => void;
function getRegisterType(eventType:string):string {
	return eventType ? eventType : "defaultType"
}

export default class EventBus {
	/**
	 * 发送粘性事件（消息，同一个类型，只保留最后一个）
	 * @param msg 消息
	 * @param eventType 事件类型
	 */
	static postSticky(msg:any, eventType:string) {
		const registerType = getRegisterType(eventType);
		const findIndex = eventsHolder.stickyEvents.findIndex(item => item.eventType === registerType);
		if (findIndex >= 0) {
			eventsHolder.stickyEvents[findIndex].msg = msg;
		} else {
			eventsHolder.stickyEvents.push({
				eventType: registerType,
				msg: msg,
			})
		}
		EventBus.post(msg, registerType);
	}

	/**
	 * 发送事件消息
	 * @param msg 消息
	 * @param eventType 事件类型
	 */
	static post(msg:any, eventType:string) {
		const postType = getRegisterType(eventType);
		eventsHolder.observerList.forEach(item => {
			if (postType === item.eventType && item.subscriber && typeof item.subscriber === "function") {
				item.subscriber({eventType: item.eventType, msg: msg});
			}
		})
	}

	/**
	 * //注册一个事件(同一类型只能注册一次，即同一函数名称名称，只能注册一次)
	 * @param observer 需要观察的对象
	 * @param eventType 观察的对象事件类型，可确省,默认为 "defaultType"
	 * @param sticky  是否是粘性事件，可确省,默认为false
	 * @param subscriber 订阅回调
	 */
	static register(observer:any, sticky:boolean = false, eventType:string = 'defaultType', subscriber:Subscriber) {
		if (subscriber) {
			const registerType = getRegisterType(eventType);
			let findIndex = eventsHolder.observerList.findIndex(item => item.observer === observer && item.eventType === eventType);
			if (findIndex < 0) {
				if (sticky) {
					let findEvent = eventsHolder.stickyEvents.find(item => item.eventType === registerType);
					if (findEvent && subscriber && typeof subscriber === "function") {
						subscriber(findEvent);
					}
				}
				eventsHolder.observerList.push({
					observer: observer,
					subscriber: subscriber,
					eventType: registerType,
				})
			}
		}
	}

	/**
	 * 解除注册
	 * @param observer
	 */
	static unregister(observer:any) {
		eventsHolder.observerList = eventsHolder.observerList.filter(item => item.observer !== observer);
	}

	/**
	 * 销毁所有(谨慎调用)
	 */
	static destroy() {
		eventsHolder.stickyEvents = []
		eventsHolder.observerList = []
	}

}
